



import re
def clean_space(text):
    """"
    处理多余的空格
    """
    match_regex = re.compile(u'[\u4e00-\u9fa5。\.,，:：《》、\(\)（）]{1} +(?<![a-zA-Z])|\d+ +| +\d+|[a-z A-Z]+')
    should_replace_list = match_regex.findall(text)
    order_replace_list = sorted(should_replace_list,key=lambda i:len(i),reverse=True)
    for i in order_replace_list:
        if i == u' ':
            continue
        new_i = i.strip()
        text = text.replace(i,new_i)
    return text

# 识别
# 可能性小
# 就
# 白名单找

import cv2

import pytesseract
from pytesseract import image_to_string,image_to_data,image_to_osd,image_to_boxes

import os
# print("温馨提示：本机为",os.cpu_count(),"核CPU")
# pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
tessdata_dir_config = '--tessdata-dir "c:\\Program Files\\Tesseract-OCR\\tessdata" --psm 6 7  --user-words "C:\\Users\\wangyu\\Desktop\\font2\\chi_sim.user-words" '


img = cv2.imread("data/0003/orgin_cells/E7.jpg",0)

# ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY| cv2.THRESH_OTSU)

# top = int(0.1 * img.shape[0])  # shape[0] = rows
# bottom = top
# left = int(0.1 * img.shape[1])  # shape[1] = cols
# right = left
# h,w = img.shape[0:2]
# img = cv2.copyMakeBorder(img,int(0.1 * h) , int(0.1 * h) ,int(0.1 * w),int(0.1 * w), cv2.BORDER_CONSTANT, value = [255, 255, 255])
# cv2.imshow("img",img)

# img = thresh
# img = img_read(r"C:\Users\wangyu\Desktop\font2\2.font.exp0.tif")
# img = img_read("data/0002/orgin_cells/P7.jpg")
# print(img.shape)
# h,w = img.shape[:2]
# img = img[int(h/20):-int(h/20),int(w/20):-int(w/20)]
# cv2.imshow('img', img)

# image_to_string(img,lang='1211',config=tessdata_dir_config)
# chi_sim简中  ell现代希腊语  lat拉丁  equ Math/equation detection(数学/方程式检测)
# text = image_to_data(img,lang='chi_sim', config=tessdata_dir_config)
text = image_to_string(img,lang='simsun',config=tessdata_dir_config)
# text = text.replace("\n", " ")
# text = text.lstrip()
print(text)
print('*'*50)
text = clean_space(text)
text = text[:-2]
print(text)
print("accuracy","ocr")
cv2.waitKey(0)
cv2.destroyAllWindows()

# from cnocr import CnOcr
#
# ocr = CnOcr()
# res = ocr.ocr_for_single_line("data/0007/orgin_cells/F3.jpg")
# print("Predicted Chars:", res)


